package com.geekgo.lucenepp.core.config.index.impl;

import com.geekgo.lucenepp.core.config.datasource.LuceneDataSource;
import com.geekgo.lucenepp.core.config.index.IndexFactory;
import com.geekgo.lucenepp.util.DateUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

/**
 * 更新索引
 *
 * @author HeHaoyang
 * @create 2017-06-15 10:33
 **/
public class UpdateIndex implements IndexFactory {


    private final Logger logger = LoggerFactory.getLogger(UpdateIndex.class);

    @Override
    public boolean updateIndex(LuceneDataSource dataSource, Term term,Document document) {
        boolean flag = true;
        long startTime = DateUtil.getDate();
        IndexWriter indexWriter = dataSource.getIndexWriter();
        try {
            indexWriter.updateDocument(term,document);
            long num = indexWriter.commit();
            indexWriter.flush();
            logger.info("更新数量:{}",num);
        } catch (IOException e) {
            logger.error("更新失败！",e);
            flag = false;
        }
        DateUtil.timeConsuming("更新内核", startTime);
        return flag;
    }

    /**
     * 先删除后添加
     * @param dataSource
     * @param term 要删除的索引
     * @param documents
     * @return
     */
    @Override
    public boolean updateIndexs(LuceneDataSource dataSource, Term term, List<Document> documents) {
        boolean flag = true;
        long startTime = DateUtil.getDate();
        IndexWriter indexWriter = dataSource.getIndexWriter();
        try {
            indexWriter.updateDocuments(term,documents);
            long num = indexWriter.commit();
            indexWriter.flush();
            logger.info("更新数量:{}",num);
        } catch (IOException e) {
            logger.error("更新失败！",e);
            flag = false;
        }
        DateUtil.timeConsuming("更新内核", startTime);
        return flag;
    }
}
